package com.wjy.game;

import java.awt.*;
import java.io.IOException;

import javax.swing.*;

import com.wjy.game.message.Request;
import com.wjy.game.utils.ProtostuffUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by yaxuSong on 2015/10/21.
 */
@Slf4j
class MessageClient extends Thread {

    MultiClient client;

    MessageClient(MultiClient client) {
        this.client = client;
    }

    public void send(Request message) {
        byte[] bytes = ProtostuffUtil.serialize(message);
        try {
            client.getOut().write(bytes, 0, bytes.length);
        } catch (IOException e) {
            log.info("向服务端发送消息发生异常，异常信息：{}", e.getMessage(), e);
        }
    }

    /**
     * 给服务器发送消息
     *
     * @param sndMessage
     */
    public void sendMessage(String sndMessage) {
        try {
            client.getOut().writeUTF(sndMessage);
            log.info("发送成功！");
        } catch (Exception ea) {
            log.error("Client.sendMessage:{}", String.valueOf(ea));
            log.error("发送失败！");
        }
    }

    /**
     * 接收各种消息
     *
     * @param recMessage
     */
    public void acceptMessage(String recMessage) {
        JDialog dlg = new JDialog(client.frame, "房间列表");
        if (recMessage.startsWith("LIST_ROOM")) {
            client.roomName = null;
            client.roomList.setText("");
            client.roomName = recMessage.split(" ");
            if (client.roomName.length >= 2) {
                dlg.setSize(390, 270);
                dlg.setResizable(false);
                dlg.setLayout(new BorderLayout());
                JPanel downPanel = new JPanel();
                downPanel.setLayout(new FlowLayout());
                downPanel.setSize(390, 100);
                downPanel.add(client.labelTitle);
                downPanel.add(client.choseTextField);
                downPanel.add(client.okButton);
                client.roomList.setSize(380, 130);
                String[] sName = recMessage.split(" ");
                client.roomName = new String[sName.length - 1];
                for (int i = 0; i < client.roomName.length; i++) {
                    if (sName[i + 1].startsWith("1")) {
                        client.roomName[i] = sName[i + 1].substring(2) + "的房间" + "-等待中";
                    }
                    if (sName[i + 1].startsWith(("2"))) {
                        String[] getTemp1 = sName[i + 1].split("-");
                        client.roomName[i] = getTemp1[1] + "与" + getTemp1[2] + "的房间" + "-游戏中";
                    }
                    client.roomList.append("[" + (i + 1) + "] " + "" + client.roomName[i] + "\r\n");
                }
                dlg.add(client.roomList, BorderLayout.NORTH);
                dlg.add(downPanel, BorderLayout.SOUTH);
                dlg.setLocation(470, 305);
                dlg.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(client.frame, "没有任何房间！", "提示", 2);
            }

        }
        // 加入成功
        if (recMessage.startsWith("JOIN_OK")) {
            log.info("加入成功！");
            dlg.setVisible(false);
            String[] getPeerName = recMessage.split(" ");
            client.setChessServerName(getPeerName[1]);
            JOptionPane.showMessageDialog(client.frame, client.getChessServerName() + "加入成功！", "提示", 2);
            client.sendButton.setEnabled(true);
            client.startButton.setEnabled(true);
            client.createRoomButton.setEnabled(false);
            client.exitRoomButton.setEnabled(true);
            client.joinButton.setEnabled(false);
            client.messageBox.setText("加入成功！请选择棋子颜色并点击“开始游戏”！");
            client.setOnChess(true);
        }
        // 对话
        if (recMessage.startsWith("TALK")) {
            String[] getInfo = recMessage.split(" ");
            String message = "";
            for (int i = 2; i < getInfo.length; i++) {
                message += getInfo[i];
            }
            client.messageBox.setText(getInfo[1] + ":" + message);
        }
        // 获胜
        if (recMessage.startsWith("WIN")) {
            client.setYourTurn(false);
            client.setOnStart(false);
            client.createRoomButton.setEnabled(true);
            client.exitRoomButton.setEnabled(false);
            client.joinButton.setEnabled(true);
            client.startButton.setEnabled(false);
            client.messageBox.setText("");
            client.setOnChess(false);
            JOptionPane.showMessageDialog(client.frame, "对方落荒而逃！您获胜了！", "提示", 1);
            for (int i1 = 0; i1 < 15; i1++) {
                for (int j1 = 0; j1 < 15; j1++) {
                    client.getChessBoard()[i1][j1] = -1;
                }
            }
            client.getCanvas().paint(client.getCanvas().getGraphics());
            client.getCanvas().update(client.getCanvas().getGraphics());
        }
        if (recMessage.equals("WAIT")) {
            log.info("wait");
            JOptionPane.showMessageDialog(client.frame, "请等待对方开始游戏！", "提示", 2);
        }
        if (recMessage.startsWith("READY")) {
            log.info("ready");
            client.setPeerColor(recMessage.substring(7));
            if (Integer.valueOf(client.getPeerColor()) == client.comboBox.getSelectedIndex()) {
                client.setPeerColor(String.valueOf((client.comboBox.getSelectedIndex() + 1) % 8));
            }
            JOptionPane.showMessageDialog(client.frame, "等待对方先下棋！", "提示", 2);
            log.info(recMessage);
        }
        if (recMessage.startsWith("FIRST")) {
            log.info("first");
            client.setPeerColor(recMessage.substring(10));
            if (Integer.valueOf(client.getPeerColor()) == client.comboBox.getSelectedIndex()) {
                client.setPeerColor(String.valueOf((client.comboBox.getSelectedIndex() + 1) % 8));
            }
            JOptionPane.showMessageDialog(client.frame, "请下棋！", "提示", 2);
            client.setYourTurn(true);
        }
        if (recMessage.startsWith("REJECT")) {
            JOptionPane.showMessageDialog(client.frame, recMessage.substring(8), "提示", JOptionPane.ERROR_MESSAGE);
        }
        // 落子
        if (recMessage.startsWith("CHESS")) {
            String[] getInfo = recMessage.split(" ");
            int x = Integer.parseInt(getInfo[2]);
            int y = Integer.parseInt(getInfo[3]);
            client.getCurrentChess().x = x;
            client.getCurrentChess().y = y;
            client.keepPoint(x, y, Integer.valueOf(client.getPeerColor()));
            client.getCanvas().paint(client.getCanvas().getGraphics());
            client.getCanvas().update(client.getCanvas().getGraphics());
            client.setYourTurn(true);
            client.repentanceButton.setEnabled(false);
        }
        // 输棋
        if (recMessage.equals("FAIL")) {
            client.comboBox.setEnabled(true);
            client.sendButton.setEnabled(false);
            client.joinButton.setEnabled(true);
            client.createRoomButton.setEnabled(true);
            client.exitRoomButton.setEnabled(false);
            client.repentanceButton.setEnabled(false);
            for (int i1 = 0; i1 < 15; i1++) {
                for (int j1 = 0; j1 < 15; j1++) {
                    client.getChessBoard()[i1][j1] = -1;
                }
            }
            client.getCanvas().paint(client.getCanvas().getGraphics());
            client.getCanvas().update(client.getCanvas().getGraphics());
            client.setYourTurn(false);
            client.setOnChess(false);
            client.setOnStart(false);
            JOptionPane.showMessageDialog(client.frame, "很糟糕你失败了！", "提示", 1);
        }
        if (recMessage.startsWith("TAKE_BACK ")) {
            int n = JOptionPane.showConfirmDialog(client.frame, "对方请求悔棋！", "提示", JOptionPane.YES_NO_OPTION);
            // 同意悔棋
            if (n == 0) {
                sendMessage("AGREE_BACK " + client.getChessServerName());
                client.setYourTurn(false);
                client.getChessBoard()[(client.getCurrentChess().x - 18) / 35][(client.getCurrentChess().y - 18) / 35] = -1;
                client.getCanvas().paint(client.getCanvas().getGraphics());
                client.getCanvas().update(client.getCanvas().getGraphics());
            }
            // 拒绝悔棋
            if (n == 1) {
                sendMessage("REFUSE_BACK " + client.getChessServerName());
            }
        }
        if (recMessage.equals("REFUSE_BACK")) {
            JOptionPane.showMessageDialog(client.frame, "对方拒绝了你的请求！", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
        if (recMessage.equals("AGREE_BACK")) {
            JOptionPane.showMessageDialog(client.frame, "对方同意了你的请求！", "提示", JOptionPane.WARNING_MESSAGE);
            client.setYourTurn(true);
            client.getChessBoard()[(client.getCurrentChess().x - 18) / 35][(client.getCurrentChess().y - 18) / 35] = -1;
            client.getCanvas().paint(client.getCanvas().getGraphics());
            client.getCanvas().update(client.getCanvas().getGraphics());
        }
    }

    @Override
    public void run() {
        String message = "";
        try {
            while (true) {
                message = client.getIn().readUTF();
                acceptMessage(message);
            }
        } catch (IOException e) {
            log.error("接收消息发生异常，异常信息：{}", e.getMessage(), e);
        }
    }

}
